"use client"

import { useState, useEffect, useCallback } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Leaf, Building, Users } from "lucide-react"
import { authAPI, institutionAPI } from "@/lib/authapi"
import { LoginForm } from "@/app/auth/LoginForm"
import { useAuth } from "@/hooks/useAuth"
import type { User, Institution, LoginRequest } from "@/types/auth"

// 登录表单数据类型
interface LoginFormData {
  email: string
  password: string
}

// 用户类型信息
interface UserTypeInfo {
  userType: 'laboratory' | 'member' | null
  fullName?: string
  institutionName?: string
  laboratoryName?: string
}

interface AuthPageProps {
  onLoginSuccess?: (user: User) => void
}

export function AuthPage({ onLoginSuccess }: AuthPageProps) {
  const { login, isLoading: authIsLoading } = useAuth()
  
  // 当前活跃的标签页
  const [activeTab, setActiveTab] = useState<'member' | 'laboratory'>('member')
  
  // 登录状态
  const [isLoading, setIsLoading] = useState(false)
  
  // 错误信息状态
  const [error, setError] = useState<string | null>(null)
  
  // 实验室成员表单
  const [memberForm, setMemberForm] = useState<LoginFormData>({
    email: '',
    password: ''
  })
  
  // 实验室表单
  const [labForm, setLabForm] = useState<LoginFormData>({
    email: '',
    password: ''
  })
  
  // 密码显示状态
  const [showMemberPassword, setShowMemberPassword] = useState(false)
  const [showLabPassword, setShowLabPassword] = useState(false)
  
  // 记住密码状态
  const [rememberMemberPassword, setRememberMemberPassword] = useState(false)
  const [rememberLabPassword, setRememberLabPassword] = useState(false)
  
  // 用户类型检查状态
  const [userTypeInfo, setUserTypeInfo] = useState<UserTypeInfo | null>(null)
  const [isCheckingUserType, setIsCheckingUserType] = useState(false)
  
  // 机构和实验室数据
  const [institutions, setInstitutions] = useState<Institution[]>([])
  
  // 从本地存储加载记住的登录信息
  useEffect(() => {
    if (typeof window !== 'undefined') {
      // 加载记住的实验室成员信息
      const savedMemberEmail = localStorage.getItem('remember_member_email')
      const savedMemberPassword = localStorage.getItem('remember_member_password')
      if (savedMemberEmail && savedMemberPassword) {
        setMemberForm({ email: savedMemberEmail, password: savedMemberPassword })
        setRememberMemberPassword(true)
      }
      
      // 加载记住的实验室信息
      const savedLabEmail = localStorage.getItem('remember_lab_email')
      const savedLabPassword = localStorage.getItem('remember_lab_password')
      if (savedLabEmail && savedLabPassword) {
        setLabForm({ email: savedLabEmail, password: savedLabPassword })
        setRememberLabPassword(true)
      }
    }
  }, [])
  
  // 检查用户类型
  const checkUserType = useCallback(async (email: string) => {
    if (!email || !email.includes('@')) {
      setUserTypeInfo(null)
      return
    }
    
    try {
      setIsCheckingUserType(true)
      const response = await authAPI.checkUserType(email) as {
        exists: boolean
        user_type?: 'laboratory' | 'member'
        full_name?: string
        institution_name?: string
        laboratory_name?: string
      }
      
      if (response.exists) {
        setUserTypeInfo({
          userType: response.user_type!,
          fullName: response.full_name,
          institutionName: response.institution_name,
          laboratoryName: response.laboratory_name
        })
      } else {
        setUserTypeInfo(null)
      }
    } catch (error) {
      console.error('Check user type failed:', error)
      setUserTypeInfo(null)
    } finally {
      setIsCheckingUserType(false)
    }
  }, [])
  
  // 处理邮箱变化
  const handleEmailChange = useCallback(async (email: string) => {
    // 防抖处理
    const timeoutId = setTimeout(() => {
      checkUserType(email)
    }, 500)
    
    return () => clearTimeout(timeoutId)
  }, [checkUserType])
  
  // 处理登录
  const handleLogin = async (
    e: React.FormEvent,
    formData: LoginFormData,
    userType: 'member' | 'laboratory'
  ) => {
    e.preventDefault()
    
    if (!formData.email || !formData.password) {
      setError('请填写邮箱和密码')
      return
    }
    
    // 检查用户类型是否匹配
    if (userTypeInfo && userTypeInfo.userType !== userType) {
      setError('请切换到正确的登录类型')
      return
    }
    
    setIsLoading(true)
    setError(null) // 清除之前的错误
    
    try {
      const credentials: LoginRequest = {
        email: formData.email,
        password: formData.password,
        user_type: userType
      }
      
      console.log('尝试登录:', { email: formData.email, userType })
      const result = await login(credentials)
      
      if (result.success) {
        console.log('登录成功')
        // 保存记住的登录信息
        if (userType === 'member' && rememberMemberPassword) {
          localStorage.setItem('remember_member_email', formData.email)
          localStorage.setItem('remember_member_password', formData.password)
        } else if (userType === 'member') {
          localStorage.removeItem('remember_member_email')
          localStorage.removeItem('remember_member_password')
        }
        
        if (userType === 'laboratory' && rememberLabPassword) {
          localStorage.setItem('remember_lab_email', formData.email)
          localStorage.setItem('remember_lab_password', formData.password)
        } else if (userType === 'laboratory') {
          localStorage.removeItem('remember_lab_email')
          localStorage.removeItem('remember_lab_password')
        }
        
        // 登录成功回调
        if (onLoginSuccess && typeof onLoginSuccess === 'function') {
          onLoginSuccess({} as User)
        }
      } else {
        console.error('登录失败:', result.message)
        setError(result.message || '登录失败，请检查邮箱和密码')
      }
    } catch (error: any) {
      console.error('登录错误:', error)
      setError(error.message || '登录过程中发生错误，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }
  
  // 加载机构数据
  useEffect(() => {
    const loadInstitutions = async () => {
      try {
        const response = await institutionAPI.getInstitutions()
        setInstitutions(response as Institution[])
      } catch (error) {
        console.error('加载机构失败:', error)
      }
    }
    
    loadInstitutions()
  }, [])



  return (
    <div className="min-h-screen bg-gradient-to-br from-green-50 to-blue-50 dark:from-gray-900 dark:to-gray-800 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* 应用标题 */}
        <div className="text-center mb-8">
          <div className="flex items-center justify-center gap-3 mb-4">
            <div className="p-3 bg-primary rounded-full">
              <Leaf className="h-8 w-8 text-primary-foreground" />
            </div>
            <div>
              <h1 className="text-3xl font-bold text-foreground font-serif">智慧农业</h1>
              <p className="text-muted-foreground">实验数据管理系统</p>
            </div>
          </div>
        </div>

        {/* 登录卡片 */}
        <Card className="shadow-xl border-0 bg-card/95 backdrop-blur">
          <CardContent>
            <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'member' | 'laboratory')} className="space-y-6">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="member" className="flex items-center gap-2">
                  <Users className="h-4 w-4" />
                  实验室成员
                </TabsTrigger>
                <TabsTrigger value="laboratory" className="flex items-center gap-2">
                  <Building className="h-4 w-4" />
                  实验室
                </TabsTrigger>
              </TabsList>

              {/* 实验室成员登录 */}
              <TabsContent value="member" className="space-y-4">
                <LoginForm
                  formData={memberForm}
                  onFormChange={setMemberForm}
                  onSubmit={(e) => handleLogin(e, memberForm, 'member')}
                  showPassword={showMemberPassword}
                  onTogglePassword={() => setShowMemberPassword(!showMemberPassword)}
                  remember={rememberMemberPassword}
                  onRememberChange={setRememberMemberPassword}
                  isLoading={isLoading || authIsLoading}
                  userType="member"
                  onEmailChange={handleEmailChange}
                  userTypeInfo={userTypeInfo}
                  isCheckingUserType={isCheckingUserType}
                  error={error}
                />
              </TabsContent>

              {/* 实验室登录 */}
              <TabsContent value="laboratory" className="space-y-4">
                <LoginForm
                  formData={labForm}
                  onFormChange={setLabForm}
                  onSubmit={(e) => handleLogin(e, labForm, 'laboratory')}
                  showPassword={showLabPassword}
                  onTogglePassword={() => setShowLabPassword(!showLabPassword)}
                  remember={rememberLabPassword}
                  onRememberChange={setRememberLabPassword}
                  isLoading={isLoading || authIsLoading}
                  userType="laboratory"
                  onEmailChange={handleEmailChange}
                  userTypeInfo={userTypeInfo}
                  isCheckingUserType={isCheckingUserType}
                  error={error}
                />
              </TabsContent>
            </Tabs>

            {/* 底部链接 */}
            <div className="text-center mt-6 pt-4 border-t space-y-3">
              <p className="text-sm text-muted-foreground">
                需要邮箱访问权限？
                <Button variant="link" className="p-0 h-auto text-primary">
                  联系管理员获取邮箱
                </Button>
              </p>
              
              {/* 测试邮箱信息 */}
              <div className="text-xs text-muted-foreground bg-muted/50 p-3 rounded-lg">
                <div className="space-y-1">
                  <p><strong>实验室成员：</strong> member@test.com / 123456</p>
                  <p><strong>实验室管理员：</strong> lab@test.com / 123456</p>
                  <p className="text-amber-600 font-medium">注意：系统将根据账户类型自动限制可选的登录方式</p>
                  <p className="text-blue-600 text-xs">• 实验室成员只能选择“实验室成员”登录</p>
                  <p className="text-blue-600 text-xs">• 实验室管理员只能选择“实验室”登录</p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 版权信息 */}
        <div className="text-center mt-8 text-sm text-muted-foreground">
          <p>© 2024 智慧农业实验数据管理系统</p>
        </div>
      </div>
    </div>
  )
}